package net.xdclass.strategy;

/**
 * 功能描述
 *
 * @author ASUS
 * @date 2024/07/27  20:15
 */

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

@Slf4j
public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String>  {
    /**
     * @param availableTargetNames 数据源集合
     * 在分库时值为所有分⽚库的集合 databaseNames
     * 分表时为对应分⽚库中所有分⽚表的集合 tablesNames
     * @param shardingValue 分⽚属性，包括
     * logicTableName 为逻辑表，
     * columnName 分⽚健字段），
     * value 为从 SQL 中解析出的分⽚健的值
     * @return
     *
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        //分库分表中availableTargetNames:["ds0","ds1","dsa"],分库分表中的shardingValues:{"columnName":"code","logicTableName":"short_link","value":"a4oeGnR1"}
        log.info("分库分表中availableTargetNames:" + JSON.toJSONString(availableTargetNames) + ",分库分表中的shardingValues:" + JSON.toJSONString(shardingValue));
        //获取短链码第⼀位，即库位
        String codePrefix = shardingValue.getValue().substring(0, 1);
        for (String targetName : availableTargetNames) {
            //获取库名的最后⼀位，真实配置的ds(dcloud_link_0,dcloud_link_1)
            String targetNameSuffix = targetName.substring(targetName.length() - 1);
            //如果⼀致则返回
            if (codePrefix.equals(targetNameSuffix))
            {
                return targetName;
            }
        }
        //抛异常
        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);
    }

}
